package com.jiefutong.zyt;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.jiefutong.zyt.apiservice.ApiService;
import com.jiefutong.zyt.bean.NewUserVO;
import com.jiefutong.zyt.fragment.MainFragment;
import com.jiefutong.zyt.fragment.MiddleFragment;
import com.jiefutong.zyt.fragment.MineFragment;

import com.jiefutong.zyt.fragment.ShopcartFragment;
import com.jiefutong.zyt.http.XCRRestProvider;
import com.jiefutong.zyt.view.MyDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhy.autolayout.AutoLayoutActivity;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;

public class TabActivity extends AutoLayoutActivity {
    private ArrayList<Fragment> fragmentArray = new ArrayList<Fragment>();
    private ViewPager mViewPage;
    private FragmentAdapter adapter;
    private int currentTabIndex = 0;
    private LinearLayout[] mTab = new LinearLayout[4];
    private TextView[] tv = new TextView[4];
    private ImageView[] iv = new ImageView[4];
    ApiService apiService= XCRRestProvider.getInstance().create(ApiService.class);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab);
        initView();
        loadcode();

    }

    private void initView() {
        mViewPage=  findViewById(R.id.main_viewPager);
        mTab[0] = (LinearLayout) findViewById(R.id.btn_home);
        mTab[1] = (LinearLayout) findViewById(R.id.btn_charge);
        mTab[2] = (LinearLayout) findViewById(R.id.btn_shopcart);
        mTab[3] = (LinearLayout) findViewById(R.id.btn_mine);

        tv[0] = (TextView) findViewById(R.id.tv_home);
        tv[1] = (TextView) findViewById(R.id.tv_charge);
        tv[2] = (TextView) findViewById(R.id.tv_shopcart);
        tv[3] = (TextView) findViewById(R.id.tv_mine);

        iv[0] = (ImageView) findViewById(R.id.iv_home);
        iv[1] = (ImageView) findViewById(R.id.iv_charge);
        iv[2] = (ImageView) findViewById(R.id.iv_shopcart);
        iv[3] = (ImageView) findViewById(R.id.iv_mine);
        MainFragment mainFragment=new MainFragment();
        MiddleFragment middleFragment=new MiddleFragment();
        ShopcartFragment shopcartFragment=new ShopcartFragment();
        MineFragment mineFragment=new MineFragment();

        fragmentArray.add(mainFragment);
        fragmentArray.add(middleFragment);
        fragmentArray.add(shopcartFragment);
        fragmentArray.add(mineFragment);
        mViewPage.setOffscreenPageLimit(4);
        adapter = new FragmentAdapter(getSupportFragmentManager());
        mViewPage.setAdapter(adapter);
        mViewPage.setCurrentItem(0);
        iv[0].setSelected(true);
        tv[0].setTextColor(0xffFC6465);
        mViewPage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                iv[currentTabIndex].setSelected(false);
                tv[currentTabIndex].setTextColor(0xff666666);
                iv[position].setSelected(true);
                tv[position].setTextColor(0xffFC6465);
                currentTabIndex = position;
            }
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }
            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        for (int i = 0; i < iv.length; i++) {
            final LinearLayout tab = mTab[i];
            tab.setTag(i);

            tab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int n = (int) tab.getTag();
                    mViewPage.setCurrentItem(n);
                }
            });
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == 100) {
           /* Bundle bundle = data.getExtras();
            if (bundle != null) {
                System.out.println("--------------result:"+bundle);
                if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_SUCCESS) {
                    String result = bundle.getString(XQRCode.RESULT_DATA);
                    *//*if (!TextUtils.isEmpty(method) && scan) {
                        mAgentWeb.getJsAccessEntrace().quickCallJs(method, result);
                        scan = false;
                        return;
                    }*//*

                    if (result.startsWith("http") || result.startsWith("https")) {
                        startActivity(new Intent(TabActivity.this, WebViewActivity.class)
                                .putExtra("url", result));
                    } else {
                        Toast.makeText(TabActivity.this, "二维码错误,请重试", Toast.LENGTH_SHORT).show();
                    }

                } else if (bundle.getInt(XQRCode.RESULT_TYPE) == XQRCode.RESULT_FAILED) {
                    Toast.makeText(TabActivity.this, "解析二维码失败", Toast.LENGTH_SHORT).show();
                }
            }*/
        }
    }

    private void loadNewUser() {
        //新人送50金币
        Call<NewUserVO> call=apiService.getNewInfo();
        call.enqueue(new Callback<NewUserVO>() {
            @Override
            public void onResponse(Call<NewUserVO> call, retrofit2.Response<NewUserVO> response) {
                if(response.isSuccessful()){
                    NewUserVO userVO=response.body();
                    if(userVO.getStatus().equals("success")){
                        input(userVO.getData());
                    }else{
                       // input(userVO.getData());
                     // Toast.makeText(getBaseContext(),userVO.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<NewUserVO> call, Throwable t) {
                Toast.makeText(getBaseContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });

    }

    //债券
    MyDialog builder;
    public void input( NewUserVO.DataBean data){
        View view=View.inflate(TabActivity.this,R.layout.dialog_new,null);
       TextView coinTV=view.findViewById(R.id.dialogNew_coinTV);
        coinTV.setText("送您"+data.getNum()+"金币");
        //coinTV.setText("送您金币");
       ImageView getIV=view.findViewById(R.id.dialogNew_getTV);
        getIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        builder = new MyDialog(TabActivity.this,0,0,view,R.style.dialog);
        builder.show();


    }

    private void loadcode() {
        OkGo.<String>post("https://zyt.jiefutong.net/update.php")
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        final InfoBean bean = JSON.parseObject(response.body(), InfoBean.class);
                        if (bean != null && bean.code == 200) {
                            int code = getVersioncode();
                            System.out.println("-----------code:"+code+"--------"+bean.data.appcode);
                            if (code < bean.data.appcode) {
                                new AlertDialog.Builder(TabActivity.this)
                                        .setTitle("升级更新")
                                        .setMessage(bean.data.app_desc)
                                        .setPositiveButton("立即升级", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                startActivity(new Intent(TabActivity.this, WebViewActivity.class).putExtra("url", bean.data.app_url).putExtra("title","app升级"));
                                                dialog.dismiss();
                                            }
                                        })
                                        .setCancelable(false)
                                        .create()
                                        .show();
                                //showpop(bean.data.app_desc, bean.data.download_url);
                            }else{
                                loadNewUser();
                            }
                        }
                    }
                });
    }


    /**
     * 获取版本号
     *
     * @return 版本号
     */
    public int getVersioncode() {
        try {
            PackageManager pm = getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }


    /**
     * 自定义adapter
     */
    class FragmentAdapter extends FragmentPagerAdapter {
        public final static int TAB_COUNT = 4;

        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentArray.get(position);
        }

        @Override
        public int getCount() {
            return fragmentArray.size();
        }
    }
}
